<?php

namespace app\admin\service\setting;

use app\common\model\auth\Admin;
use app\common\model\log\ExportFileLog;
use tmcore\base\BaseService;
use tmcore\exceptions\ValidateException;

/**
 * 导出日志服务类
 */
class ExportService extends BaseService
{
    /**
     * 获取导出日志列表
     * @return array
     */
    public static function getList(): array
    {
        // 搜索条件
        $searchParam = [
            '%like%' => ['file_name','file_url'],
            '=' => ['result'],
            'datetime' => ['create_time'],
        ];
        $where = self::getSearchData($searchParam, []);

        // 返回分页数据
        return ExportFileLog::page($where, self::getPageData(),'id,type,file_identifier,file_name,result,result_msg,file_suffix,file_url,size,count,create_time', ['id' => 'desc'], ['result_desc','type_desc'] );
    }

    /**
     * 查看日志详情
     * @param $params
     * @return array
     */
    public static function detail($params) : array
    {
        if(empty($params['id'])) throw new ValidateException('参数异常');
        $row = ExportFileLog::where(['id' => $params['id']])->append(['result_desc','type_desc'])->hidden(['job,export_job'])
            ->findOrEmpty();
        if ($row->isEmpty()) return [];
        $row['admin_name'] = $row['admin_id']?Admin::where('id', $row['admin_id'])->value('name'):'';
        return $row->toArray();
    }

    /**
     * 查看日志详情
     * @param $params
     * @return null
     */
    public static function download($params)
    {
        if(empty($params['id'])) throw new ValidateException('参数异常');
        $file_url = ExportFileLog::where(['id' => $params['id']])->value('file_url');
        if (!$file_url) throw new ValidateException('文件路径为空，不可下载');
        header("Access-Control-Expose-Headers:Content-Disposition");
        return download( app()->getRootPath() . $file_url, urlencode(substr($file_url, strrpos($file_url, '/') + 1)));
    }

    /**
     * 删除导出日志
     * @param array $params
     * @return mixed
     */
    public static function delete($params)
    {
        if(empty($params['id'])) throw new ValidateException('参数异常');
        $row = ExportFileLog::where(['id' => $params['id']])->field('id,result,file_url')->findOrEmpty();
        $res = ExportFileLog::del($params['id']);
        if(!$res) throw new ValidateException('删除失败');
        if($row['result'] == 1 && $row['file_url']) unlink(app()->getRootPath() . $row['file_url']);
        return true;
    }
}